package com.zhihui.client.alarm.controller;


import com.zhihui.client.alarm.common.JsonData;
import com.zhihui.client.alarm.common.RequestHolder;
import com.zhihui.client.alarm.entity.User;
import com.zhihui.client.alarm.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import java.io.IOException;

/**
 * 已登陆用户操作
 * @author: Lenovo
 * @date 2018/10/15 20:46
 */
@RestController
public class UserController {
    @Resource
   private UserService userService;

    /**
     * 登录 2018-08-29 19:16:30
     * @param username
     * @param password
     * @return
     * @throws IOException
     * @throws ServletException
     */
    @ApiOperation(value = "登陆",notes = "传入账号密码")
    @PostMapping("/login.json")
    public JsonData login(String username, String password) throws IOException, ServletException {
        String errorMsg = "";
        User sysPersonal;
        if (StringUtils.isBlank(username)) {
            errorMsg = "用户名不可以为空";
        } else if (StringUtils.isBlank(password)) {
            errorMsg = "密码不可以为空";
        }
        if (StringUtils.isBlank(errorMsg)) {
            sysPersonal = userService.login(username);
        } else {
            return JsonData.fail(errorMsg);
        }
        if (sysPersonal == null) {
            errorMsg = "请输入正确用户名";
        } else if (!sysPersonal.getPassword().equals(DigestUtils.md2Hex(password))) {
            errorMsg = "用户名或密码错误";
        } else if (sysPersonal.getPassword().equals(DigestUtils.md2Hex(password))) {
            RequestHolder.add(sysPersonal);
            return JsonData.success();
        }
        return JsonData.fail(errorMsg);
    }

    /**
     * 注销
     * 2018-08-29 19:39:26
     * @return
     */
    @ApiOperation(value = "注销")
    @PostMapping("/logout")
    public void logout() {
        RequestHolder.remove();
    }

    /**
     * 注销
     * 2018-08-29 19:39:26
     * @return
     */
    @ApiOperation(value = "获取自身信息")
    @PostMapping("/getInformation.json")
    public JsonData getInformation() {
      return JsonData.success(RequestHolder.getCurrentUser());
    }


}
